<?php
/**
 * 门票管理
 *
 * @copyright  Copyright (c) 2015-2025 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com/
 * @link       http://www.ncphp.com/
 * @author	   NcPHP Team
 * @since      File available since Release v2.1
 */
defined('InNcPHP') or exit('Access Invalid!');

class ticketControl extends SystemControl{
	private $links = array(
		array('url'=>'act=ticket&op=index','lang'=>'nc_manage'),
		array('url'=>'act=ticket&op=add','lang'=>'nc_new'),
	);

	public function __construct(){
		parent::__construct();
		Language::read('ticket');
	}

	/**
	 * 门票列表
	 */
	public function indexOp(){
	    /* @var ticketModel $ticket_model */
	    $ticket_model = Model('ticket');
        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        /* @var ticket_categoryModel $category_model */
        $category_model = Model('ticket_category');
        $cates = $category_model->getCategoryList();

        //查询条件
	    $condition = array();
	    if (isset($_GET['search_title']) && $_GET['search_title']) {
	        $condition['tk_title'] = array('like', '%' . trim($_GET['search_title']) . '%');
        }
        if (isset($_GET['search_state']) && is_numeric($_GET['search_state'])) {
	        $condition['tk_status'] = intval($_GET['search_state']);
        }
        if (isset($_GET['search_cate1']) && is_numeric($_GET['search_cate1'])) {
	        $condition['tk_cate1'] = intval($_GET['search_cate1']);
        }
        if (isset($_GET['search_cate2']) && is_numeric($_GET['search_cate2'])) {
            $condition['tk_cate2'] = intval($_GET['search_cate2']);
            $defaultCate2 = $category_model->getCategoryList(array('tc_pid'=>$condition['tk_cate1']));
            Tpl::output('defaultCate2', $defaultCate2);
        }
        $merchant_id = intval($this->admin_info['merchant_id']);
        if($merchant_id>0){
            $condition['merchant_id'] = $merchant_id;
        }else{
            if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
                $condition['merchant_id'] = intval($_GET['search_merchant']);
            }
        }

        $day = getgpc('day');
        if($day=='today'){
            $time_from = $time_to = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d"),date("Y")))) ;
            $time_to = $time_to + 86400;
            $condition['tk_add_time'] = array('between',array($time_from,$time_to));
        }


        setcookie('ticketback', $_SERVER['QUERY_STRING']);
        //查询列表
        /* @var ticket_skuModel $sku_model */
        $sku_model = Model('ticket_sku');
	    $tickets = $ticket_model->getTicketListPage($condition, '*', 10);
        foreach ($tickets as $k => $ticket) {
            $tickets[$k]['shop_name'] = $merchant_model->getfby_merchant_id($ticket['merchant_id'], 'mc_shop_name');
            $tickets[$k]['tk_thumb'] = UPLOAD . 'product/' . $tickets[$k]['tk_thumb'];
            foreach ($cates as $cate) {
                if ($ticket['tk_cate1'] == $cate['tc_id']) {
                    $tickets[$k]['tk_cate1'] = $cate['tc_name'];
                } else if ($ticket['tk_cate2'] == $cate['tc_id']) {
                    $tickets[$k]['tk_cate2'] = $cate['tc_name'];
                }
            }
            //固定价格，获取SKU
            if ($ticket['type'] == 0) {
                $tickets[$k]['sku'] = $sku_model->getTicketSkuList(array('tk_id'=>$ticket['tk_id']));
            }
	    }

        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }

        $cate1 = $category_model->getCategoryList(array('tc_pid'=>TICKET_MARK,'is_del'=>0));//门票底下所有分类

        Tpl::output('search', $_GET);
        Tpl::output('tickets',$tickets);
        Tpl::output('merchants', $merchants);
        Tpl::output('cate1', $cate1);
        Tpl::output('cates', $cates);
        Tpl::output('page',$ticket_model->showpage());

        Tpl::output('top_link',$this->sublink($this->links,'index'));
        Tpl::showpage('ticket.index');
	}

    /**
     * 添加门票
     */
	public function addOp(){
        /* @var areaModel $area_model */
        $area_model = Model('area');

        if (chksubmit()) {
            /* @var ticketModel $ticket_model */
            $ticket_model = Model('ticket');
            $time = time();
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $params = array(
                'merchant_id' => intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']),
                'tk_title' => $_POST['title'],
                'tk_subtitle' => $_POST['subtitle'],
                'tk_cate1' => $_POST['cate1'],
               /* 'tk_cate2' => $_POST['cate2'],*/
                'tk_type' => $_POST['type'],
                'tk_show_price' => floatval($_POST['show_price']),
                'tk_market_price' => floatval($_POST['tk_market_price']),
                'tk_is_discount' => $_POST['is_discount'],
                'tk_is_recommend' => $_POST['is_recommend'],
                'tk_irecommend' => $_POST['irecommend'],
                'tk_province_id' => $_POST['province_id'],
                'tk_city_id' => $_POST['city_id'],
                'tk_city_name' => $area_model->getfby_area_id($_POST['city_id'],'name'),
                'tk_area_id' => $_POST['area_id'],
                'tk_addr' => $_POST['addr'],
                'tk_detail' => $_POST['content'],
                'tk_tips' => $_POST['content1'],
                'tk_add_time' => $time,
                'tk_update_time' => $time,
                'tk_lat'=>$store_gps[1],
                'tk_lng'=>$store_gps[0],
                'tk_tel'=>$_POST['tk_tel'],
            );
            $params['tk_full_addr'] = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $params['tk_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));
            //封面图片
            $upload = new UploadFile();
            $upload->set('max_size', 2048);
            $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            $result = $upload->upfile('thumb');
            if($result){
                $params['tk_thumb'] = $upload->getSysSetPath() . $upload->file_name;
            } else {
                //图片上传失败
                $this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
                showMessage(L('nc_common_save_fail').$upload->error);
            }
            //音频上传

            $upload1 = new UploadVideoFile();
            $_filepath1 = 'video/' . $upload1->getSysSetPath();
            $upload1->set('default_dir', $_filepath1);
            $upload1->set('max_size', 102400);
            if($_FILES['video']['name']){
                $result1	= $upload1->upfile('video');
                if($result1){
                    $params['audio'] = $upload1->getSysSetPath() . $upload1->file_name;
                }else{
                    //$this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
                    showMessage(L('nc_common_save_fail').$upload1->error);
                }
            }
            $spec_model = Model('spec');
            //数据库操作
            Model::beginTransaction();
            try {
                //插入
                $tk_id = $ticket_model->addTicket($params);
                /* @var ticket_skuModel $sku_model */

                //插入门票的规格
                if($tk_id){
                    $data = array(
                        'goods_id' =>$tk_id,
                        'add_time' =>time(),
                        'type' =>2 //门票
                    );
                    foreach($_POST['spec_name'] as $k => $v)
                    {
                        $data['spec_sort']    = $_POST['gs_sort'][$k];
                        $data['spec_name']    = $_POST['spec_name'][$k];
                        $data['cost_price']   = $_POST['cost_price'][$k];
                        $data['market_price'] = $_POST['market_price'][$k];
                        $data['price']        = $_POST['price'][$k];
                        $data['is_show']      = $_POST['spec_is_show'][$k];
                        //$data['stock']        = $_POST['stock'][$k];
                        $data['label']        = $_POST['label'][$k];
                        $spec_model->addSpec($data);
                    }
                }
                Model::commit();
                $res = true;
            } catch (\Exception $e) {
                Model::rollback();
                $res = false;
            }
            //操作结果
            if ($res) {
                $url = array(
                    array(
                        'url' => 'index.php?act=ticket&op=photo&tk_id='.$tk_id,
                        'msg' => '上传图片'
                    ),
                );
                $this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',1);
                showMessage(L('nc_common_save_succ'), $url);
            } else {
                $this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
                showMessage(L('nc_common_save_fail'));
            }
        }


	    /* @var member_merchantModel $merchant_model */
	    $merchant_model = Model('member_merchant');
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        /* @var ticket_categoryModel $category_model */
	    $category_model = Model('ticket_category');
        $cate1 = $category_model->getCategoryList(array('tc_pid'=>TICKET_MARK, 'is_del'=>0));//获取门票底下所有分类

        $provinces = $area_model->getAreaList(array('parent_id'=>1));


        //获取所有门票类型
        $types = Model('ticket_type')->getTicketTypeList();
        Tpl::output('types', $types);

        Tpl::output('merchants', $merchants);
        Tpl::output('cate1', $cate1);
        Tpl::output('provinces', $provinces);

        Tpl::output('top_link',$this->sublink($this->links,'add'));
        Tpl::showpage('ticket.add');
    }

    /**
     * 编辑
     */
    public function editOp()
    {
        /* @var ticketModel $ticket_model */
        $ticket_model = Model('ticket');
        /* @var ticket_skuModel $sku_model */
        $sku_model = Model('ticket_sku');
        /* @var areaModel $area_model */
        $area_model = Model('area');
        $spec_model = Model('spec');
        if (chksubmit()) {
            $time = time();
            $tk_id = $_POST['tk_id'];
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $params = array(
                'merchant_id' => intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']),
                'tk_title' => $_POST['title'],
                'tk_subtitle' => $_POST['subtitle'],
                'tk_cate1' => $_POST['cate1'],
                //'tk_cate2' => $_POST['cate2'],
                'tk_type' => $_POST['type'],
                'tk_show_price' => floatval($_POST['show_price']),
                'tk_market_price' => floatval($_POST['tk_market_price']),
                'tk_is_discount' => $_POST['is_discount'],
                'tk_is_recommend' => $_POST['is_recommend'],
                'tk_irecommend' => $_POST['irecommend'],
                'tk_province_id' => $_POST['province_id'],
                'tk_city_id' => $_POST['city_id'],
                'tk_city_name' => $area_model->getfby_area_id($_POST['city_id'],'name'),
                'tk_area_id' => $_POST['area_id'],
                'tk_addr' => $_POST['addr'],
                'tk_detail' => $_POST['content'],
                'tk_tips' => $_POST['content1'],
                'tk_add_time' => $time,
                'tk_update_time' => $time,
                'tk_lat'=>$store_gps[1],
                'tk_lng'=>$store_gps[0],
                'tk_tel'=>$_POST['tk_tel'],
            );
            $params['tk_full_addr'] = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $params['tk_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));

            //如果有重新上传的话
            if ($_FILES['thumb']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
                $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
                $upload->set('thumb_ext', GOODS_IMAGES_EXT);
                $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
                //封面图片
                $result = $upload->upfile('thumb');
                if($result){
                    //得到图片上传后的路径
                    $params['tk_thumb'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'[tk_id:'.$tk_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            $upload1 = new UploadVideoFile();
            $_filepath1 = 'video/' . $upload1->getSysSetPath();
            $upload1->set('default_dir', $_filepath1);
            $upload1->set('max_size', 102400);
            if($_FILES['video']['name']){
                $result1	= $upload1->upfile('video');
                if($result1){
                    $params['audio'] = $upload1->getSysSetPath() . $upload1->file_name;
                }else{
                    //$this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
                    showMessage(L('nc_common_save_fail').$upload1->error);
                }
            }

            //数据库操作


                $res = $ticket_model->updateTicket(array('tk_id'=>$tk_id), $params);


                 if(count($_POST['spec_name'])>0){
                     foreach($_POST['spec_name'] as $k => $v)
                     {
                         $spec_id = $_POST['spec_id'][$k];
                         $data['goods_id'] =  $tk_id;
                         $data['spec_sort']   = $_POST['gs_sort'][$k];
                         $data['spec_name']    = $_POST['spec_name'][$k];
                         $data['cost_price'] = $_POST['cost_price'][$k];
                         $data['market_price'] = $_POST['market_price'][$k];
                         $data['price']        = $_POST['price'][$k];
                         $data['is_show']      = $_POST['spec_is_show'][$k];
                         //$data['stock']        = $_POST['stock'][$k];
                         $data['label']        = $_POST['label'][$k];
                         if(empty($spec_id)){
                             $data['type']         = 2;
                             $data['add_time'] = time();
                             $spec_model->addSpec($data);
                         }else{
                             $spec_model->updateSpec(array('spec_id'=>$spec_id),$data);
                         }
                     }
                 }


            //操作结果
            if ($res) {
                $this->log(L('nc_edit,ticket_index_ticket').'[tk_id:'.$tk_id.']',1);
                showMessage(L('nc_common_save_succ'), 'index.php?'.$_COOKIE['ticketback']);
            } else {
                $this->log(L('nc_edit,ticket_index_ticket').'[tk_id:'.$tk_id.']',0);
                showMessage(L('nc_common_save_fail'));
            }
        }

        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        /* @var ticket_categoryModel $category_model */
        $category_model = Model('ticket_category');
        $cate1 = $category_model->getCategoryList(array('tc_pid'=>2,'is_del'=>0));//景区分类列表

        $provinces = $area_model->getAreaList(array('parent_id'=>1));

        //查询门票信息
        $tk_id = intval($_GET['tk_id']);
        $ticket = $ticket_model->getTicketInfo(array('tk_id'=>$tk_id));
        $ticket['tk_thumb'] = UPLOAD . 'product/' . $ticket['tk_thumb'];
        $ticket['tk_face'] = UPLOAD . 'product/' . $ticket['tk_face'];
        $ticket['sku'] = $sku_model->getTicketSkuList(array('tk_id'=>$tk_id));
        if($ticket['audio']){
            $ticket['audio'] = UPLOAD.'video/'.$ticket['audio'];
        }
        //获取所有门票类型
        $types = Model('ticket_type')->getTicketTypeList();
        Tpl::output('types', $types);

        //获取已经选中市、县
        $citys = $area_model->getAreaList(array('parent_id'=>$ticket['tk_province_id']));
        $areas = $area_model->getAreaList(array('parent_id'=>$ticket['tk_city_id']));
        //获取已经选中的二级分类
        $cate2 = $category_model->getCategoryList(array('tc_pid'=>2,'is_del'=>0));

        //获取门票下的所有类型
        $spec_list = $spec_model->getSpecListPage(array('goods_id'=>$tk_id,'type'=>2,'parent_id'=>0));
        Tpl::output('spec_list',$spec_list);
        Tpl::output('ticket', $ticket);
        Tpl::output('merchants', $merchants);
        Tpl::output('cate1', $cate1);
        Tpl::output('cate2', $cate2);
        Tpl::output('provinces', $provinces);
        Tpl::output('citys', $citys);
        Tpl::output('areas', $areas);

        array_push($this->links, array('url'=>'act=ticket&op=edit&tk_id=' . $tk_id,'lang'=>'nc_edit'));
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=ticket&op=edit&tk_id=' . $tk_id,'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=ticket&op=photo&tk_id=' . $tk_id,'lang'=>'ticket_index_photo')
        );
        Tpl::output('sub_link',$this->sublink($sublinks,'edit'));
        Tpl::showpage('ticket.edit');
    }

    /**
     * ajax更改状态
     */
    public function ajaxOp()
    {
        /* @var ticketModel $ticket_model */
        $ticket_model = Model('ticket');

        $type = $_GET['type'];
        switch ($type) {
            case 'change_recommend':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getTicketInfo(array('tk_id'=>$tk_id));
                if ($tk) {
                    $recommend = $tk['tk_is_recommend'] ? 0 : 1;
                    $res = $ticket_model->updateTicket(array('tk_id'=>$tk_id), array('tk_is_recommend'=>$recommend));
                    $action = $recommend ? 'ticket_add_recommend' : 'ticket_index_not_recommend';
                    $this->log(L('ticket_index_ticket,'.$action).'[tk_id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_recommend'=>$recommend)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_recommend'=>'')));
                }
            case 'change_status':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getTicketInfo(array('tk_id'=>$tk_id));
                if ($tk) {
                    $status = $tk['tk_status'] ? 0 : 1;
                    $res = $ticket_model->updateTicket(array('tk_id'=>$tk_id), array('tk_status'=>$status));
                    $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                    $this->log(L('ticket_index_ticket,'.$action).'[tk_id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_status'=>$status)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_status'=>'')));
                }
            case 'change_all':
                $ids = $_POST['ids'];
                $status = $_POST['type'] == 'show' ? 1 : 0;
                $condition = array(
                    'tk_id' => array('in', implode(',', $ids))
                );
                $res = $ticket_model->updateTicket($condition, array('tk_status'=>$status));
                $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                $this->log(L('ticket_index_ticket,'.$action).'[tk_id:'.implode(',',$ids).']', $res?1:0);
                exit(json_encode(array('res'=>$res)));
        }
    }

    /**
     * 门票相册
     */
    public function photoOp()
    {
        $tk_id = intval($_GET['tk_id']);
        /* @var ticket_imagesModel $images_model */
        $images_model = Model('ticket_images');

        if ($_FILES) {
            $upload = new UploadFile();
            $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            $result = $upload->upfile('file');
            if($result){
                //得到图片上传后的路径
                $path = $upload->getSysSetPath() . $upload->file_name;
                $params = array(
                    'tk_id' => $tk_id,
                    'img_size' => round($_FILES['file']['size'] / 1024),
                    'img_ext' => $upload->ext,
                    'img_path' => $path,
                    'img_addtime' => time(),
                    'type'=>2
                );
                //保存到数据库
                if ($img_id = $images_model->addTicketImage($params)) {
                    $this->log(L('nc_add,ticket_index_photo').'[tk_id:'.$tk_id.'][img_id:'.$img_id.']', 1);
                    exit(json_encode(array(
                        'res' => true,
                        'id' => $img_id,
                        'path' => UPLOAD . 'product/' . $path
                    )));
                }
            }
            $this->log(L('nc_add,ticket_index_photo').'[tk_id:'.$tk_id.']', 0);
            exit(json_encode(array('res'=>false)));
        }

        Tpl::output('tk_id', $tk_id);
        $images = $images_model->getTicketImageList(array('tk_id'=>$tk_id, 'img_deleted'=>0,'type'=>2));
        foreach ($images as $k => $img) {
            $images[$k]['img_path'] = UPLOAD . 'product/' . $img['img_path'];
        }
        Tpl::output('images',$images);

        array_push($this->links, array('url'=>'act=ticket&op=edit&tk_id=' . $tk_id,'lang'=>'nc_edit'));
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=ticket&op=edit&tk_id=' . $tk_id,'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=ticket&op=photo&tk_id=' . $tk_id,'lang'=>'ticket_index_photo')
        );
        Tpl::output('sub_link',$this->sublink($sublinks,'photo'));
        Tpl::showpage('ticket.photo');
    }

    /**
     * ajax删除照片
     */
    public function delimgOp()
    {
        $img_id = intval($_POST['img_id']);
        /* @var ticket_imagesModel $images_model */
        $images_model = Model('ticket_images');
        $res = $images_model->delTicketImage(array('img_id'=>$img_id));
        $this->log(L('nc_del,ticket_index_photo').'[img_id:'.$img_id.']', $res?1:0);
        exit(json_encode(array('res'=>$res)));
    }

    /**
     * 设置每天的售价
     */
    public function daysOp()
    {
        $tk_id = intval($_GET['tk_id']);

        /* @var ticket_dateModel $date_model */
        $date_model = Model('ticket_date');
        /* @var ticket_sku_dateModel $sku_model */
        $sku_model = Model('ticket_sku_date');
        /* @var ticketModel $ticket */
        $ticket = Model('ticket');
        /* @var ticket_typeModel $type_model */
        $type_model = Model('ticket_type');
        /* @var specModel $spec_model */
        $spec_model = Model('spec');
        $date_list = $date_model->getTicketDateListPage(array('tk_id'=>$tk_id), '*', 10);
        foreach ($date_list as $k => $date) {
            $date_list[$k]['sku'] = $sku_model->getTicketSpecSkuList(array('date_id'=>$date['date_id']));
        }

        //所有门票种类
        $types = $type_model->getTicketTypeList();
        Tpl::output('types', $types);

        //门票详情
        $ticketInfo = $ticket->getTicketInfo(array('tk_id'=>$tk_id));
        Tpl::output('ticket', $ticketInfo);

        //获取该门票底下的所有规格
        $spec_list = $spec_model->getSpecList(array('goods_id'=>$tk_id,'type'=>2));

        Tpl::output('spec_list',$spec_list);
        Tpl::output('list', $date_list);
        Tpl::output('page',$date_model->showpage());
        //顶部链接
        array_push($this->links, array('url'=>'act=ticket&op=days&tk_id=' . $tk_id,'lang'=>'ticket_index_date'));
        Tpl::output('top_link',$this->sublink($this->links,'days'));
        Tpl::showpage('ticket.days');
    }

    /**
     * 每日价格ajax操作
     */
    public function days_ajaxOp(){
        $lang	= Language::getLangContent();
        $type = $_GET['type'];

        /* @var ticket_dateModel $date_model */
        $date_model = Model('ticket_date');
        /* @var ticket_sku_dateModel $sku_model */
        $sku_model = Model('ticket_sku_date');
        //var_dump($_POST);exit;

        //exit;
        switch ($type) {
            case 'add':
                $time = time();
                $params = array(
                    'tk_id' => intval($_POST['tk_id']),
                    'date' => $_POST['date']
                );
                $old = $date_model->getTicketDateInfo($params);

                if ($old) {
                    $res = json_encode(array('res'=>false, 'msg'=>$lang['ticket_day_date_same']));
                } else {
                    Model::beginTransaction();
                    try {
                        $params['date_time'] = $time;
                        $date_id = $date_model->addTicketDate($params);
                        if ($date_id) {
                           /* foreach ($_POST['types'] as $key => $val) {
                                $sku_params = array(
                                    'date_id' => $date_id,
                                    'type_id' => intval($key),
                                    'sku_store' => intval($_POST['store'.$key]),
                                    'sku_price' => floatval($_POST['price'.$key]),
                                    'sku_time' => $time
                                );
                                //$sku_model->addTicketSku($sku_params);
                            }*/

                            foreach ($_POST['types'] as $key => $val) {
                               foreach($_POST['store'] as $ks=>$vo){
                                    if($_POST['price'][$ks][$key]>0){
                                        $sku_params = array(
                                            'date_id'=>$date_id,
                                            'spec_id'=>$key,
                                            'sku_store'=>intval($vo[$key]),
                                            'sku_price'=>floatval($_POST['price'][$ks][$key]),
                                            'sku_cost_price'=>floatval($_POST['cost_price'][$ks][$key]),
                                            'sku_time'=>$time,
                                            'type_id'=>$ks
                                        );
                                        $sku_model->addTicketSku($sku_params);
                                    }
                               }

                            }
                            Model::commit();
                            $res = json_encode(array('res'=>true, 'msg'=>$lang['nc_common_save_succ']));
                        } else {
                            Model::rollback();
                            $res = json_encode(array('res'=>false, 'msg'=>$lang['nc_common_save_fail']));
                        }
                    } catch(\Exception $e) {
                        Model::rollback();
                        $res = json_encode(array('res'=>false, 'msg'=>$lang['nc_common_save_fail']));
                    }
                }
                exit($res);
            case 'info':
                $date_id = $_POST['date_id'];
                $date_info = $date_model->getTicketDateInfo(array('date_id'=>$date_id));
                $date_info['sku'] = $sku_model->getTicketSpecSkuList(array('date_id'=>$date_id));
               // var_dump($date_info);exit;
                exit(json_encode($date_info));
            case 'update':
                $date_id = $_POST['date_id'];
                $types = array_keys($_POST['types']);
                $time = time();
               // var_dump($_POST);exit;
                Model::beginTransaction();
                try {
                    //删除已经无用的sku
                    $types && $sku_model->delTicketSku(array(
                        'date_id' => $date_id,
                        'spec_id' => array('not in', implode(',', $types))
                    ));
                    foreach ($types as $type_id) {
                        foreach($_POST['store'] as $ks=>$vo){
                            $sku_params = array(
                                'date_id' => $date_id,
                                'spec_id'=>$type_id,
                                'sku_store'=>intval($vo[$type_id]),
                                'sku_price'=>floatval($_POST['price'][$ks][$type_id]),
                                'sku_cost_price'=>floatval($_POST['cost_price'][$ks][$type_id]),
                                'sku_time'=>$time,
                                'type_id'=>$ks
                            );
                            if($_POST['price'][$ks][$type_id]>0){
                                $old_sku = $sku_model->getTicketSpecSku(array('date_id'=>$date_id,'ticket_sku_date.spec_id'=>$type_id,'ticket_sku_date.type_id'=>$ks));
                                 if ($old_sku) {
                                    $sku_model->updateTicketSku(array('sku_id'=>$old_sku['sku_id']), $sku_params);
                                } else {
                                    $sku_model->addTicketSku($sku_params);
                                }
                            }else{
                                //删除本条SKU
                                $sku_model->delTicketSku(array('date_id'=>$date_id,'spec_id'=>$type_id,'type_id'=>$ks));
                            }


                        }
                    }

                    Model::commit();
                    $res = true;
                } catch (\Exception $e) {
                    Model::rollback();
                    $res = false;
                }
                $this->log(L('nc_edit,ticket_index_date').'[date_id:'.$date_id.']', $res ? 1 : 0);
                exit(json_encode(array('res'=>$res)));
            case 'del':
                $date_id = $_POST['date_id'];
                Model::beginTransaction();
                $res = $date_model->delTicketDate(array('date_id'=>$date_id)) && $sku_model->delTicketSku(array('date_id'=>$date_id));
                $res ? Model::commit() : Model::rollback();
                $this->log(L('nc_del,ticket_index_date').'[date_id:'.$date_id.']', $res?1:0);
                exit(json_encode(array('res'=>$res)));
            case 'del_all':
                $ids = $_POST['ids'];
                $condition = array(
                    'date_id' => array('in', implode(',', $ids))
                );
                Model::beginTransaction();
                $res = $date_model->delTicketDate($condition) && $sku_model->delTicketSku($condition);
                $res ? Model::commit() : Model::rollback();
                $this->log(L('nc_del,ticket_index_date').'[date_id:'.implode(',', $ids).']', $res?1:0);
                exit(json_encode(array('res'=>$res)));
        }
    }
    /**
     * 编辑规格
     */
    public function spec_editOp()
    {
        $spec_model = Model('spec');
        $all_spec_id = intval($_GET['spec_id']);
        $spec_info = $spec_model->getSpecInfo(array('spec_id'=>$all_spec_id));
        /* @var ticket_skuModel $sku_model */
        $sku_model = Model('ticket_sku');
        /* @var ticket_typeModel $type_model */
        $type_model = Model('ticket_type');
        if(chksubmit()){

            $update_array = array();
            $update_array['spec_name'] = $_POST['all_spec_name'];
            //$update_array['cost_price'] = $_POST['cost_price_'];
            //$update_array['market_price'] = $_POST['all_market_price'];
            $update_array['label'] = $_POST['all_label'];
            //$update_array['stock'] = $_POST['all_stock'];
            $update_array['is_show'] = $_POST['is_show'];
            $update_array['open_spec'] = $_POST['open_spec'];
            $update_array['detail'] = $_POST['content'];
            $update_array['tips'] = $_POST['content1'];
            //var_dump($_POST);exit;
            if($_FILES['thumb']['tmp_name']){
                $upload = new UploadFile();
                $upload->set('default_dir','ticket/'.$upload->getSysSetPath());
                $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
                $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
                $upload->set('thumb_ext', GOODS_IMAGES_EXT);
                $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
                //封面图片
                $result = $upload->upfile('thumb');
                if($result){
                    $update_array['surface_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log('类型封面图上传失败'.'[标题:'.$_POST['title'].']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }

            if(isset($_POST['types']) && is_array($_POST['types']) && count($_POST['types'])>0){
                    //先删除sku 再添加
                $sku_model->delTicketSku(array('spec_id'=>$all_spec_id));
                foreach ($_POST['types'] as $key => $val) {
                    $sku_params = array(
                        'tk_id' => $spec_info['goods_id'],
                        'type_id' => $key,
                        'sku_store' => intval($_POST['store'.$key]),
                        'sku_price' => floatval($_POST['price'.$key]),
                        'sku_cost_price'=>floatval($_POST['cost_price'.$key]),
                        'sku_time' => time(),
                        'spec_id'=>$all_spec_id
                    );
                    $old_sku = $sku_model->getTicketSpecSku(array('ticket_sku.spec_id'=>$all_spec_id,'ticket_sku.type_id'=>$key));
                    if ($old_sku) {
                        $sku_model->updateTicketSku(array('sku_id'=>$old_sku['sku_id']), $sku_params);
                    } else {
                        $sku_model->addTicketSku($sku_params);
                    }
                }
            }else{
                showMessage('请至少选择一个票券类型');
            }

            $result = $spec_model->updateSpec(array('spec_id'=>$all_spec_id,'type'=>2),$update_array);
            if($result){
                $this->log('编辑票型成功'.'[标题:'.$_POST['all_spec_name'].']',1);
                showMessage(L('nc_common_save_succ'),'index.php?act=ticket&op=edit&tk_id='.$spec_info['goods_id']);
            }else{
                showMessage(L('nc_common_save_fail'));
            }
        }
        //var_dump($spec_info);exit;
        $sublinks = array(
            array('url'=>'act=ticket&op=edit&tk_id=' . $spec_info['goods_id'],'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=ticket&op=spec_edit&spec_id=' . $spec_id,'lang'=>'ticket_index_type')
        );
        //获取房型所有类型
        $spec_list = $spec_model->getSpecListPage(array('type'=>1,'parent_id'=>$all_spec_id));
        //获取封面图
        $spec_info['surface_img'] = getGoodsImg($spec_info['surface_img'],TICKET_MARK);
        //获取图册
        $images_model = Model('spec_images');
        $images = $images_model->getSpecImageList(array('spec_id'=>$all_spec_id, 'img_deleted'=>0));
        if(!empty($images)){
            foreach($images as $key => $vo){
                $images[$key]['img_path'] = getGoodsImg($vo['img_path'],TICKET_MARK);
            }
        }
        $spec_info['sku'] = $sku_model->getTicketSpecSkuList(array('ticket_sku.spec_id'=>$all_spec_id));
        //所有门票种类
        $types = $type_model->getTicketTypeList();
        Tpl::output('types',$types);
        Tpl::output('images',$images);
        Tpl::output('spec_list',$spec_list);
        Tpl::output('spec_info',$spec_info);
        Tpl::output('sub_link',$this->sublink($sublinks,'spec_edit'));
        Tpl::showpage('ticket_spec_edit');
    }

    /**
     * ajax 上传图片
     */
    public function ajax_imgsOp()
    {
        $images_model = Model('spec_images');
        $spec_id = intval($_GET['spec_id']);
        $upload = new UploadFile();
        $upload->set('default_dir', 'ticket/' . $upload->getSysSetPath());
        $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
        $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
        $upload->set('thumb_ext', GOODS_IMAGES_EXT);
        $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
        $result = $upload->upfile('file');
        if($result){
            //得到图片上传后的路径
            $path = $upload->getSysSetPath() . $upload->file_name;
            $params = array(
                'spec_id' => $spec_id,
                'img_size' => round($_FILES['file']['size'] / 1024),
                'img_ext' => $upload->ext,
                'img_path' => $path,
                'img_addtime' => time(),
            );
            //保存到数据库
            if ($img_id = $images_model->addSpecImage($params)) {
                $this->log('添加景点图册'.'[景点ID:'.$spec_id.'][img_id:'.$img_id.']', 1);
                exit(json_encode(array(
                    'res' => true,
                    'id' => $img_id,
                    'path' => UPLOAD . 'ticket/' . $path
                )));
            }
        }
        $this->log('添加景点图册'.'[景点ID:'.$spec_id.']', 0);
        exit(json_encode(array('res'=>false)));
    }
    /**
     * 删除规格
     */
    public function delete_specOp()
    {
        $spec_id = intval($_POST['spec_id']);
        $spec_model = Model('spec');
        if($spec_id>0){
            $condition = array();
            $info = $spec_model->getSpecInfo(array('spec_id'=>$spec_id));
            if(empty($info)){
                die(json_encode(array('tab' => 'error', 'info' => '规格不存在')));
            }

            $condition['spec_id'] = $spec_id;
            $condition['type'] = 2;
            if($spec_model->deleteSpec($condition)){
                $spec_model->deleteSpec(array('parent_id'=>$spec_id));//删除底下的子分类
                die(json_encode(array('tab' => 'success', 'info' => '删除成功')));
            }
            die(json_encode(array('tab' => 'error', 'info' => '删除失败')));
        }
        die(json_encode(array('tab' => 'error', 'info' => '非法操作')));
    }

    /**
     * 删除门票
     */
    public function del_ticketOp()
    {
        $tk_id = $_POST['tk_id'];
        if($tk_id>0){
            /* @var ticketModel $ticket_model */
            $ticket_model = Model('ticket');
            /* @var specModel $spec_model */
            $spec_model = Model('spec');
            $tk = $ticket_model->getTicketInfo(array('tk_id'=>$tk_id));
            if($tk){
                $res = $ticket_model->deleteTicket(array('tk_id'=>$tk_id));
                //删除门票底下所有规格
                $res_ = $spec_model->deleteSpec(array('goods_id'=>$tk_id,'type'=>TICKET_MARK));
                if($res && $res_){
                    exit(json_encode(array('res'=>true, 'msg_'=>'成功')));
                }else{
                    exit(json_encode(array('res'=>false, 'msg_'=>'删除失败')));
                }
            }else{
                exit(json_encode(array('res'=>false, 'msg_'=>'门票不存在')));
            }
        }
    }
}